package cn.big.bigd.biocode.configure;

import cn.big.bigd.biocode.dao.UserDAO;
import cn.big.bigd.biocode.model.Role;
import cn.big.bigd.biocode.model.User;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static org.slf4j.LoggerFactory.getLogger;

@Component
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private static final Logger logger = getLogger(CustomAuthenticationSuccessHandler.class);

    public CustomAuthenticationSuccessHandler() {
    }

    @Autowired
    private UserDAO userDAO;

    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        boolean admin = false;
        HttpSession httpSession = request.getSession();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = userDetails.getUsername();
        User user = userDAO.findByEmailOrUsername(username, username);
        httpSession.setAttribute("currentUser", user);

        for (GrantedAuthority auth : authentication.getAuthorities()) {
            System.out.println(auth.getAuthority());
            if ((Role.ADMIN.getName()).equals(auth.getAuthority())) {
                admin = true;
            }
        }
        if (admin) {
            super.setDefaultTargetUrl("/admin/home");
        } else {
            super.setDefaultTargetUrl("/curator/home");
        }

        super.onAuthenticationSuccess(request, response, authentication);
    }
}